package com.landeb.shop.huo.frag;

import android.app.Dialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatDialog;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.landeb.shop.R;
import com.landeb.shop.huo.MyApplication;
import com.landeb.shop.huo.act.GoodDetailActivity;
import com.landeb.shop.huo.act.SearchActivity;
import com.landeb.shop.huo.adapter.FragProductsGVAdapter;
import com.landeb.shop.huo.adapter.FragProductsLVAdapter;
import com.landeb.shop.huo.bean.BeanProductFragLeftLv;
import com.landeb.shop.huo.bean.BeanProductFragRightGv;
import com.landeb.shop.huo.eventMsg.MsgSelectedId;
import com.landeb.shop.huo.httpRequest.FragProductsRequest;
import com.landeb.shop.huo.view.FixedGridView;
import com.landeb.shop.huo.view.FootView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;


public class ProductsFragment extends Fragment implements View.OnClickListener {
    private static final String BASE_URL = "baseUrl";

    @BindView(R.id.frag_products_tv_location1)
    TextView mFragProductsTvLocation1;
    @BindView(R.id.frag_products_ll_location1)
    LinearLayout mFragProductsLlLocation1;
    @BindView(R.id.frag_products_tv_location2)
    TextView mFragProductsTvLocation2;
    @BindView(R.id.frag_products_ll_location2)
    LinearLayout mFragProductsLlLocation2;
    @BindView(R.id.frag_products_tv_location3)
    TextView mFragProductsTvLocation3;
    @BindView(R.id.frag_products_ll_location3)
    LinearLayout mFragProductsLlLocation3;
    @BindView(R.id.frag_products_tv_location4)
    TextView mFragProductsTvLocation4;
    @BindView(R.id.frag_products_ll_location4)
    LinearLayout mFragProductsLlLocation4;
    @BindView(R.id.frag_products_tv_location5)
    TextView mFragProductsTvLocation5;
    @BindView(R.id.frag_products_ll_location5)
    LinearLayout mFragProductsLlLocation5;
    @BindView(R.id.frag_products_tv_location6)
    TextView mFragProductsTvLocation6;
    @BindView(R.id.frag_products_ll_location6)
    LinearLayout mFragProductsLlLocation6;
    @BindView(R.id.frag_products_ll_location_container)
    LinearLayout mFragProductsLlLocationContainer;

    Unbinder unbinder;

    private String mBaseUrl;

    private View view;
    private Button btnSearch;
    private LinearLayout btnScan, btnMsg;
    private SwipeRefreshLayout mSRL;
    private ListView mLeftListView;
    private ScrollView mRightScrollView;
    //    private TextView tvTop, tvFoot;
    private FixedGridView gvTop;
    private FootView mFootView;
    private ScrollView mScrollView;
    private LinearLayout mGvContainer;
//    private FixedGridView gvFoot;

    //    private List<ItemFragProductsListView> channelList;
    private List<BeanProductFragRightGv.DataBean.ListBean> productGvList;
//    private List<ItemFragProductsGridView> footGvList;

    private FragProductsLVAdapter mListAdapter;
    private FragProductsGVAdapter GvAdapter;
//    private FragProductsGVAdapter footGvAdapter;

    private String mTestBaseUrl;
    private Retrofit mRetrofit;
    private FragProductsRequest mFragProductsRequest;
    private BeanProductFragLeftLv mProducts;
    private List<BeanProductFragLeftLv.DataBean> mProductsList;

    private boolean isRefreshing = false;
    private int selectedId = 0;

    private boolean isLoaded = false;
    private boolean isViewPrepared = false; // 标识fragment视图已经初始化完毕

    private int mPage = 0;
    private boolean isAdding = false;
    private boolean hasNextPage = true;

    private List<BeanProductFragLeftLv.DataBean.ChildBean> mLocations = new ArrayList<>();
    private List<LinearLayout> mLocationLl = new ArrayList<>();
    private List<TextView> mLocationTv = new ArrayList<>();

    private String nowLocationId = "";
    private String msgId = "";

    private boolean fromJsonParse = false;

    public ProductsFragment() {
        // Required empty public constructor
    }

    public static ProductsFragment newInstance(String baseUrl) {
        ProductsFragment fragment = new ProductsFragment();
        Bundle args = new Bundle();
        args.putString(BASE_URL, baseUrl);
        fragment.setArguments(args);
        return fragment;
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void selectList(MsgSelectedId msg) {


        msgId = msg.getSelected();

        refreshBySelectedId();
        mLeftListView.setSelection(3);
        Toast.makeText(getContext(), mListAdapter.getSelectPosition() + "", Toast.LENGTH_SHORT).show();

//        mListAdapter.changeSelected(3);

////        getProductList();
////        selectedId=getMsgIndex(msg.getSelected());
////        Log.e("selectList: ",selectedId+"");
    }

    private void refreshBySelectedId() {

        mFragProductsRequest.getProductsList()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<BeanProductFragLeftLv>() {
                    @Override
                    public void onCompleted() {
                        Log.e("refreshData", "successed");
//                            isRefreshing = false;
//                            mSRL.setRefreshing(false);
                    }

                    @Override
                    public void onError(Throwable e) {
                        Log.e("refreshData", "onError");
                        e.printStackTrace();
//                            isRefreshing = false;
//                            mSRL.setRefreshing(false);

                        Toast.makeText(getContext(), "数据加载失败，请重试", Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onNext(BeanProductFragLeftLv beanProductFragLeftLv) {

                        if (beanProductFragLeftLv.getStatus() == 0) {

                            Toast.makeText(getContext(), beanProductFragLeftLv.getInfo(), Toast.LENGTH_SHORT).show();

                            return;

                        }

                        mProducts = beanProductFragLeftLv;
                        //刷新频道list
                        mProductsList.clear();
                        mProductsList.addAll(mProducts.getData());
                        mListAdapter.notifyDataSetChanged();

                        //获取地址
                        mLocations.clear();
                        if (beanProductFragLeftLv.getData().get(0).getChild().size() > 0) {
                            mLocations.addAll(beanProductFragLeftLv.getData().get(0).getChild());
//                            Log.e( " setLocations: ", beanProductFragLeftLv.getData().get(0).getChild().size() +"++++"+
//                            mLocations.size());
                            setLocations();
                        }

                        if (!TextUtils.isEmpty(msgId)) {
                            selectedId = getMsgIndex(msgId);
                            Log.e("refreshId:+++ ", selectedId + "");

                            mListAdapter.changeSelected(selectedId);

                            Log.e("getSP: ", mListAdapter.getSelectPosition() + "");

                            if (selectedId == 0) {
                                mFragProductsLlLocationContainer.setVisibility(View.VISIBLE);
                            } else {
                                mFragProductsLlLocationContainer.setVisibility(View.GONE);
                                nowLocationId = "";
                            }

                            refreshProductData(mProductsList.get(selectedId).getId());
                        }

                        if (selectedId == 0) {
                            mFragProductsLlLocationContainer.setVisibility(View.VISIBLE);
                        } else {
                            mFragProductsLlLocationContainer.setVisibility(View.GONE);
                        }


//                        mListAdapter.changeSelected(selectedId);
//                        mListAdapter.notifyDataSetChanged();

//                        refreshProductData(mProductsList.get(selectedId).getId());
//                        mLeftListView.performItemClick(mLeftListView.getChildAt(selectedId), selectedId, mLeftListView.getItemIdAtPosition(selectedId));
//                        AdapterView.OnItemClickListener onItemClickListener = mLeftListView.getOnItemClickListener();
//                        if(onItemClickListener!=null){
//                            onItemClickListener.onItemClick(mLeftListView,mLeftListView.getChildAt(selectedId),selectedId,0);
//                            Log.e( "click: ", "done" );
//                        }

                    }
                });
    }

    private int getMsgIndex(String checkId) {

        Log.e("getMsgIndex: ", mProductsList.size() + "");

        if (mProductsList == null) {
            return -1;
        }

        for (int i = 0; i < mProductsList.size(); i++) {
            if (mProductsList.get(i).getId().equals(checkId)) {
                Log.e("getMsgIndex: ", mProductsList.get(i).getId());

                return i;
            }
        }

        return -1;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mBaseUrl = getArguments().getString(BASE_URL);
        }

        //  初始化网络读取组件
        OkHttpClient client = MyApplication.getClient();
        mTestBaseUrl = MyApplication.BASE_URL;
        mRetrofit = new Retrofit.Builder()
                .baseUrl(mTestBaseUrl)
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .client(client)
                .build();
        mFragProductsRequest = mRetrofit.create(FragProductsRequest.class);

        EventBus.getDefault().register(this);

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        view = inflater.inflate(R.layout.fragment_products, container, false);
        unbinder = ButterKnife.bind(this, view);

        initView();
        initData();
        initEvent();
//        refreshData();

        setChecked(mFragProductsTvLocation1);

//        isViewPrepared = true;
//        if (!isLoaded && getUserVisibleHint()) {
        refreshData();
//            isLoaded = true;
//        }

        return view;
    }


    private void initEvent() {

        btnScan.setOnClickListener(this);
        btnSearch.setOnClickListener(this);
        btnMsg.setOnClickListener(this);

        mListAdapter = new FragProductsLVAdapter(getContext(), mProductsList);
        mLeftListView.setAdapter(mListAdapter);
        mLeftListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                // TODO: 2016/10/21 与右侧scrollview联动
//                选中变色
                Log.e("onItemClick: ", "doClick");

                mListAdapter.changeSelected(position);

                selectedId = position;

//                productGvList.clear();
                if (selectedId == 0) {
                    mFragProductsLlLocationContainer.setVisibility(View.VISIBLE);
                } else {
                    mFragProductsLlLocationContainer.setVisibility(View.GONE);
                    nowLocationId = "";
                }

                refreshProductData(mProductsList.get(position).getId());
//                if (mProductsList.get(position).getChild() != null) {
//                    productGvList.addAll(mProductsList.get(position).getChild());
//                }
//                GvAdapter.notifyDataSetChanged();
//                Toast.makeText(getContext(), channelList.get(position).getChannelName(), Toast.LENGTH_SHORT).show();
            }
        });

        GvAdapter = new FragProductsGVAdapter(getContext(), productGvList);
        gvTop.setAdapter(GvAdapter);
        gvTop.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {

                String ID = productGvList.get(i).getGoods_id();
                String title = productGvList.get(i).getName();
                String price = productGvList.get(i).getPrice();

                GoodDetailActivity.toAct(getActivity(), ID, title, price);

//                String cid = mProductsList.get(selectedId).getChild().get(i).getId() + "";
//
//                SearchResultActivity.toAct(getContext(), SearchResultActivity.FLAG_CID, cid);
            }
        });

        mSRL.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                refreshData();
            }
        });
//        footGvAdapter = new FragProductsGVAdapter(getContext(), footGvList);
//        gvFoot.setAdapter(footGvAdapter);

        mScrollView.setOnTouchListener(new View.OnTouchListener() {

            private int lastY = 0;

            @Override
            public boolean onTouch(View v, MotionEvent event) {

                if (event.getAction() == MotionEvent.ACTION_UP) {
                    lastY = mScrollView.getScrollY();
                    if (lastY == (mGvContainer.getHeight() - mScrollView.getHeight())) {
                        // TODO: 2016/10/17 判断scrollview滑动到底部 给底部gridview添加数据
//                        Toast.makeText(getContext(), "滑动到底部了", Toast.LENGTH_SHORT).show();
                        addProductData(mProductsList.get(selectedId).getId());
                    }
                }
                return false;
            }
        });


        mFragProductsLlLocation1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                setChecked(mFragProductsTvLocation1);
                nowLocationId = mLocations.get(0).getId();
                refreshProductData(mProductsList.get(selectedId).getId());

                Log.e("getClick: ", mListAdapter.getSelectPosition() + "");
            }
        });

        mFragProductsLlLocation2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                setChecked(mFragProductsTvLocation2);
                nowLocationId = mLocations.get(1).getId();
                refreshProductData(mProductsList.get(selectedId).getId());
            }
        });

        mFragProductsLlLocation3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                setChecked(mFragProductsTvLocation3);
                nowLocationId = mLocations.get(2).getId();
                refreshProductData(mProductsList.get(selectedId).getId());
            }
        });

        mFragProductsLlLocation4.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                setChecked(mFragProductsTvLocation4);
                nowLocationId = mLocations.get(3).getId();
                refreshProductData(mProductsList.get(selectedId).getId());
            }
        });

        mFragProductsLlLocation5.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                setChecked(mFragProductsTvLocation5);
                nowLocationId = mLocations.get(4).getId();
                refreshProductData(mProductsList.get(selectedId).getId());
            }
        });

        mFragProductsLlLocation6.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                setChecked(mFragProductsTvLocation6);

                AlertDialog.Builder builder = new AlertDialog.Builder(getContext());

                String[] citys = new String[mLocations.size()];
                for (int i = 0; i < mLocations.size(); i++) {
                    citys[i] = mLocations.get(i).getCatename();
                }

                String[] trimCities = Arrays.copyOfRange(citys, 6, citys.length);

                builder.setItems(trimCities, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
// TODO: 2017/8/26 点击切换城市
                        nowLocationId = mLocations.get(which + 6).getId();
                        refreshProductData(mProductsList.get(selectedId).getId());
                        mFragProductsTvLocation6.setText(mLocations.get(which + 6).getCatename());
                    }
                });
                builder.create().show();
            }
        });
    }

    private void initData() {

//        channelList = new ArrayList<>();

//        ItemFragProductsListView channel1 = new ItemFragProductsListView("1", "热门推荐");
//        ItemFragProductsListView channel2 = new ItemFragProductsListView("2", "水果蔬菜");
//        ItemFragProductsListView channel3 = new ItemFragProductsListView("3", "畜牧水产");
//        ItemFragProductsListView channel4 = new ItemFragProductsListView("4", "粮油米面");
//        ItemFragProductsListView channel5 = new ItemFragProductsListView("5", "农副加工");
//        ItemFragProductsListView channel6 = new ItemFragProductsListView("6", "农资产品");
//        ItemFragProductsListView channel7 = new ItemFragProductsListView("7", "苗木花草");
//        channelList.add(channel1);
//        channelList.add(channel2);
//        channelList.add(channel3);
//        channelList.add(channel4);
//        channelList.add(channel5);
//        channelList.add(channel6);
//        channelList.add(channel7);

        productGvList = new ArrayList<>();
        mProductsList = new ArrayList<>();
//        for (int i = 0; i < 19; i++) {
//            ItemFragProductsGridView item = new ItemFragProductsGridView("", "" + i, "");
//            productGvList.add(item);
//        }

//        footGvList = new ArrayList<>();
//        for (int i = 0; i < 21; i++) {
//            ItemFragProductsGridView item = new ItemFragProductsGridView("", "" + i, "");
//            footGvList.add(item);
//        }

        mLocationLl.add(mFragProductsLlLocation1);
        mLocationLl.add(mFragProductsLlLocation2);
        mLocationLl.add(mFragProductsLlLocation3);
        mLocationLl.add(mFragProductsLlLocation4);
        mLocationLl.add(mFragProductsLlLocation5);
        mLocationLl.add(mFragProductsLlLocation6);

        mLocationTv.add(mFragProductsTvLocation1);
        mLocationTv.add(mFragProductsTvLocation2);
        mLocationTv.add(mFragProductsTvLocation3);
        mLocationTv.add(mFragProductsTvLocation4);
        mLocationTv.add(mFragProductsTvLocation5);
        mLocationTv.add(mFragProductsTvLocation6);


    }

    private void initView() {
        btnScan = (LinearLayout) view.findViewById(R.id.frag_products_btn_scan);
        btnSearch = (Button) view.findViewById(R.id.frag_products_btn_search);
        btnMsg = (LinearLayout) view.findViewById(R.id.frag_products_btn_message);
        mLeftListView = (ListView) view.findViewById(R.id.frag_products_listView);

//        tvTop = (TextView) view.findViewById(R.id.frag_products_tv_top_title);
//        tvFoot = (TextView) view.findViewById(R.id.frag_products_tv_foot_title);
        gvTop = (FixedGridView) view.findViewById(R.id.frag_products_gv_top);
//        gvFoot = (FixedGridView) view.findViewById(R.id.frag_products_gv_foot);
        mSRL = (SwipeRefreshLayout) view.findViewById(R.id.frag_products_srl);
        mSRL.setColorSchemeColors(getResources().getColor(R.color.colorPrimary));

        mFootView = (FootView) view.findViewById(R.id.frag_products_footview);

        mScrollView = (ScrollView) view.findViewById(R.id.frag_products_scrollview);
        mGvContainer = (LinearLayout) view.findViewById(R.id.frag_products_gv_container);

//        mFragProductsTvLocation1= (TextView) view.findViewById(R.id.frag_products_tv_location1);
//        mFragProductsTvLocation2= (TextView) view.findViewById(R.id.frag_products_tv_location2);
//        mFragProductsTvLocation3= (TextView) view.findViewById(R.id.frag_products_tv_location3);
//        mFragProductsTvLocation4= (TextView) view.findViewById(R.id.frag_products_tv_location4);
//        mFragProductsTvLocation5= (TextView) view.findViewById(R.id.frag_products_tv_location5);
//        mFragProductsTvLocation6= (TextView) view.findViewById(R.id.frag_products_tv_location6);

    }


    @Override
    public void onClick(View v) {

        switch (v.getId()) {
            case R.id.frag_products_btn_scan:
                // TODO: 2016/10/17 frag home扫一扫按钮
//                Toast.makeText(getContext(), v.getId() + "", Toast.LENGTH_SHORT).show();
                break;
            case R.id.frag_products_btn_search:
                // TODO: 2016/10/17  frag home搜索按钮
//                Toast.makeText(getContext(), v.getId() + "", Toast.LENGTH_SHORT).show();
                SearchActivity.toAct(getContext());
                break;
            case R.id.frag_products_btn_message:
                // TODO: 2016/10/17  frag home消息按钮
//                Toast.makeText(getContext(), v.getId() + "", Toast.LENGTH_SHORT).show();
                break;
        }

    }

//    @Override
//    public void setUserVisibleHint(boolean isVisibleToUser) {
//        super.setUserVisibleHint(isVisibleToUser);
//        if (isVisibleToUser) {
//
//            if (isViewPrepared && !isLoaded) {
//                refreshData();
//                isLoaded = true;
//            }
//        }
//
//    }


    @Override
    public void onDestroy() {
        super.onDestroy();

        isViewPrepared = false;
        isLoaded = false;

        EventBus.getDefault().unregister(this);
    }


    private void getProductList() {


        mFragProductsRequest.getProductsList()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<BeanProductFragLeftLv>() {
                    @Override
                    public void onCompleted() {
                        Log.e("refreshData", "successed");
//                            isRefreshing = false;
//                            mSRL.setRefreshing(false);
                    }

                    @Override
                    public void onError(Throwable e) {
                        Log.e("refreshData", "onError");
                        e.printStackTrace();
//                            isRefreshing = false;
//                            mSRL.setRefreshing(false);

                        Toast.makeText(getContext(), "数据加载失败，请重试", Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onNext(BeanProductFragLeftLv beanProductFragLeftLv) {

                        if (beanProductFragLeftLv.getStatus() == 0) {

                            Toast.makeText(getContext(), beanProductFragLeftLv.getInfo(), Toast.LENGTH_SHORT).show();

                            return;

                        }

                        mProducts = beanProductFragLeftLv;
                        //刷新频道list
                        mProductsList.clear();
                        mProductsList.addAll(mProducts.getData());
                        mListAdapter.notifyDataSetChanged();

                        //获取地址
                        mLocations.clear();
                        if (beanProductFragLeftLv.getData().get(0).getChild().size() > 0) {
                            mLocations.addAll(beanProductFragLeftLv.getData().get(0).getChild());
//                            Log.e( " setLocations: ", beanProductFragLeftLv.getData().get(0).getChild().size() +"++++"+
//                            mLocations.size());
                            setLocations();
                        }

//                        if (!TextUtils.isEmpty(msgId)) {
//                          selectedId=getMsgIndex(msgId);
//                            Log.e( "refreshId: ", selectedId+"");
////                            mListAdapter.changeSelected(selectedId);
//                        }

                        if (selectedId == 0) {
                            mFragProductsLlLocationContainer.setVisibility(View.VISIBLE);
                        } else {
                            mFragProductsLlLocationContainer.setVisibility(View.GONE);
                        }

                        String cid = mProducts.getData().get(0).getId();
                        refreshProductData(cid);
//                            /*初始化频道list第一个项目所对应的gridView*/
//                            productGvList.clear();
//                            productGvList.addAll(mProductsList.get(selectedId).getChild());
//                            GvAdapter.notifyDataSetChanged();

//                            if (mProductsList.size() >= 1) {
//                                mLeftListView.setItemChecked(0,true);
//                            }
                    }
                });
//        }

    }

    private void setLocations() {

//        for (int i = 0; i <5 ; i++) {
//            mLocationTv.get(i).setText(mLocations.get(i).getCatename());
//            Log.e("setLocations: ", mLocations.get(i).getCatename());
//        }
        mFragProductsTvLocation1.setText(mLocations.get(0).getCatename());
        mFragProductsTvLocation2.setText(mLocations.get(1).getCatename());
        mFragProductsTvLocation3.setText(mLocations.get(2).getCatename());
        mFragProductsTvLocation4.setText(mLocations.get(3).getCatename());
        mFragProductsTvLocation5.setText(mLocations.get(4).getCatename());

    }

    private void setChecked(TextView tv) {

        for (TextView t : mLocationTv) {
            t.setBackgroundDrawable(getContext().getResources().getDrawable(R.drawable.shape_primary_btn_default));
        }

        tv.setBackgroundDrawable(getContext().getResources().getDrawable(R.drawable.shape_primary_btn_selected));
        if (tv.getId() != R.id.frag_products_tv_location6) {
            mFragProductsTvLocation6.setText("更多");
        }
    }

    private void refreshProductData(String cid) {

        if (!isRefreshing) {

            isRefreshing = true;
            mSRL.setRefreshing(true);

            mPage = 0;
            hasNextPage = true;

            mFragProductsRequest.getProductsData(cid, "0", nowLocationId)
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Subscriber<BeanProductFragRightGv>() {
                        @Override
                        public void onCompleted() {
                            isRefreshing = false;
                            mSRL.setRefreshing(false);
                        }

                        @Override
                        public void onError(Throwable e) {
                            Toast.makeText(getContext(), "数据加载失败，请重试", Toast.LENGTH_SHORT).show();
                            isRefreshing = false;
                            mSRL.setRefreshing(false);
                        }

                        @Override
                        public void onNext(BeanProductFragRightGv beanProductFragRightGv) {

                            if (beanProductFragRightGv.getStatus() == 0) {

                                Toast.makeText(getContext(), beanProductFragRightGv.getInfo(), Toast.LENGTH_SHORT).show();

                                return;

                            }

                            productGvList.clear();
                            productGvList.addAll(beanProductFragRightGv.getData().getList());
                            GvAdapter.notifyDataSetChanged();

                            if (beanProductFragRightGv.getData().getMore() == 1) {
                                hasNextPage = true;
                                mFootView.setToRefresh();
                            } else {
                                hasNextPage = false;
                                mFootView.setFinished();

                            }

                        }
                    });

        }


    }

    private void addProductData(String cid) {

        if (!isAdding && hasNextPage) {

            isAdding = true;
            mFootView.setRefreshing();

            mPage++;

            mFragProductsRequest.getProductsData(cid, mPage + "", nowLocationId)
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Subscriber<BeanProductFragRightGv>() {
                        @Override
                        public void onCompleted() {
                            isAdding = false;
                        }

                        @Override
                        public void onError(Throwable e) {
                            isAdding = false;
                            mFootView.setFinished();
                            Toast.makeText(getContext(), "数据加载失败，请重试", Toast.LENGTH_SHORT).show();

                        }

                        @Override
                        public void onNext(BeanProductFragRightGv beanProductFragRightGv) {

                            if (beanProductFragRightGv.getStatus() == 0) {

                                Toast.makeText(getContext(), beanProductFragRightGv.getInfo(), Toast.LENGTH_SHORT).show();

                                mFootView.setFinished();

                                return;

                            }
                            productGvList.addAll(beanProductFragRightGv.getData().getList());
                            GvAdapter.notifyDataSetChanged();

                            if (beanProductFragRightGv.getData().getMore() == 1) {
                                hasNextPage = true;
                                mFootView.setToRefresh();
                            } else {
                                hasNextPage = false;
                                mFootView.setFinished();

                            }

                        }
                    });
        }

    }


    private void refreshData() {

        Log.e("refreshData: ", "proLoaded");

        if (mProductsList.size() == 0) {
            getProductList();
            return;
        }

        refreshProductData(mProductsList.get(selectedId).getId());

    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    public void setListSelection(String cid) {

        if (getMsgIndex(cid) == -1) return;

        selectedId = getMsgIndex(cid);

        mListAdapter.changeSelected(selectedId);

        if (selectedId == 0) {
            mFragProductsLlLocationContainer.setVisibility(View.VISIBLE);
        } else {
            mFragProductsLlLocationContainer.setVisibility(View.GONE);
            nowLocationId = "";
        }

        refreshProductData(mProductsList.get(selectedId).getId());
    }
}
